package xianchenglock1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @功能
 * @创建时间 2019/12/19
 * 这时应该考虑counterdownlatch/cyclibarrier/semaphore //门栓
 * 这个不是上锁，只是t1满足条件后门栓拉开，t2进行运作
 *
 */
public class MyContainer4 {
    //添加v。。。 使t2能得到通知
    volatile List lists = new ArrayList();
    public void add(Object o){
        lists.add(o);
    }
    public int size(){
        return lists.size();
    }

    public static void main(String[] args) {
        MyContainer4 c = new MyContainer4();
        CountDownLatch latch = new CountDownLatch(1); // 一把栓
 //       final Object lock = new Object();
        new Thread(()->{

                System.out.println("t2启动");
                if(c.size()!=5){
                    try{
                      latch.await();

                      // 也可以指定等待时间
                        //   latch.await(5000,TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println("T2 结束");
                }

        },"t2").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            System.out.println("t1启动");

                for(int i=0;i<10;i++){
                    c.add(new Object());
                    System.out.println("add"+i);
                    if(c.size() == 5){

                            latch.countDown();
                    }
                    try{
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            System.out.println("t1结束");
        },"t1").start();
    }
}
